#include <stdio.h>
#include <stdlib.h>

#include "../utils/map.h"

typedef struct {
    char* name;
    int id;
} Task;

void printTask(Any  data) {
    Task* t = (Task*)data;
    printf("%s(id:%d)", t->name, t->id);
}

void hashmap_str_print(HashMap *map) {
    if (!map) return;
    for (size_t i = 0; i < map->capacity; i++) {
        printf("[%ld] ", i);
        kvPair *current = map->buckets[i];
        while (current) {
            TopoNode *node = (TopoNode*)current->value;
            Task* task = (Task*)node->data;
            printf("{%s->%d} ", task->name, task->id);
            current = current->next;
        }
        printf("\n");
    }
}

int main() {
    Task tasks[] = {
        {"Initialize", 1},
        {"LoadConfig", 2},
        {"ConnectDB", 3},
        {"StartService", 4},
        {"RunTests", 5},
        {"Stopped",6}
    };

    // 创建hashmap图
    HashMap* graph = hashmap_create(16, 0, 0, string_hash, string_compare, NULL, NULL);
    // 添加节点
    for (int i = 0; i < 6; i++) {
        printf("添加节点：%s -> %d\n", tasks[i].name,tasks[i].id);
        hashmap_add_topo_node(graph, tasks[i].name, &tasks[i]);
    }
    // 建立依赖关系
    printf("建立依赖关系:\n");
    hashmap_add_topo_dependence(graph, tasks[0].name, tasks[1].name); // 1 -> 2
    hashmap_add_topo_dependence(graph, tasks[0].name, tasks[2].name); // 1 -> 3
    hashmap_add_topo_dependence(graph, tasks[1].name, tasks[3].name); // 2 -> 4
    hashmap_add_topo_dependence(graph, tasks[2].name, tasks[3].name); // 3 -> 4
    hashmap_add_topo_dependence(graph, tasks[3].name, tasks[4].name); // 4 -> 5
    hashmap_add_topo_dependence(graph, tasks[3].name, tasks[5].name); // 4 -> 6
    hashmap_add_topo_dependence(graph, tasks[4].name, tasks[5].name); // 5 -> 6
    printf("图中节点数量：%ld\n", graph->size);
    // hashmap_str_print(graph);
    // 计算拓扑排序
    TopoSortResult result = {NULL,NULL,0,0};
    hashmap_topo_sort(graph, &result);
    
    hashmap_str_print(graph);
    // 打印结果
    if (result.size == 0)
    {
        printf("图中存在环路！\n");
    }else {
        printf("拓扑排序结果（总批次：%d）:\n", result.totalBatches);
        for (size_t i = 0; i < result.size; i++) {
            printTask(result.order[i]);
            printf(" -> 批次 %d\n", result.batches[i]);
        }
        free(result.order);
        free(result.batches);
    }
    return 0;
}
